<!--  -->
<template>
  <div class="app-container">
    <el-card style="height: 80px; margin-bottom: 10px;">
  <div style="margin-bottom: 20px;">
    <el-row :guest="20">
      <el-col :span="6">
        <el-input v-model="query.name" placeholder="请输入姓名或手机号" clearable @clear="getAdminList" />
      </el-col>
      <el-col :span="2">
        <el-button type="success" style="margin-left: 10px;" icon="el-icon-search" size="medium" @click="getAdminList">
          搜索
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" size="medium" @click="add"
        v-hasPermi="['/system/admin/saveAdmin']">
          添加
        </el-button>
      </el-col>
    </el-row>
  </div>
</el-card>

<el-card>
    <el-table
      v-loading="listLoading"
      :data="list" 
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" align="center" width="60" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.telephone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="310px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state" @change="adminStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="success" icon="el-icon-circle-plus-outline" size="mini" plain round 
            @click="toAssignRole(row)"
            v-hasPermi="['/system/admin/assignRole']">
            分配角色
          </el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" plain round @click="handleUpdate(row)"
            v-hasPermi="['/system/admin/updateState']">
            编辑
          </el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" plain round @click="handleDelete(row,$index)"
          v-hasPermi="['/system/admin/delAdmin/**']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="totalCount>0" :total="totalCount" :page.sync="query.currPageNo" :limit.sync="query.pageSize" @pagination="getAdminList" />
 </el-card>
<!-- START 添加操作员弹出对话框窗口 START -->
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
  <el-form ref="dataFormRef" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 600px; margin-left:40px;">
    <el-row>
      <el-col :span="10">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="temp.username" placeholder="登录名" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" type="password" placeholder="密码" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="姓名" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="手机" prop="phone">
          <el-input v-model="temp.phone" placeholder="手机" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="10">
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="temp.telephone" placeholder="电话" />
        </el-form-item>
      </el-col>
      <el-col :span="12" :offset="1">
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" placeholder="地址" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="头像" prop="userFace">
      <el-input v-model="temp.userFace" style="display: none" class="id" />
      <single-upload v-model="temp.userFace" />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="temp.remark" :autosize="{ minRows: 3, maxRows: 6}" type="textarea" placeholder="请输入备注内容" />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelEvent()">
      取消
    </el-button>
    <el-button type="primary" @click="dialogStatus==='create'?insertData():updateData()">
      确认
    </el-button>
  </div>
</el-dialog>
<!-- END 添加操作员弹出对话框窗口 END -->
<!-- START 分配角色对话框窗口 START -->
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="400px">
  <el-form ref="assignRoleRef" :model="assignRole" label-position="left" label-width="70px" style="width: 350px; margin-left:30px;">
    <el-form-item label="角色名">
      <el-tree
        ref="roleRef"
        class="tree-border"
        :data="roleOptions"
        show-checkbox
        node-key="id"
        empty-text="加载中，请稍候"
        :props="defaultProps"
      />
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelAssign()">
      取消
    </el-button>
    <el-button type="primary" @click="confirmAssign()">
      确认
    </el-button>
  </div>
</el-dialog>
<!-- END 分配角色对话框窗口 END -->


  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
// 从src/api/user.js中解构出pageUserList()方法并在当前组件中导入
import { pageUserList,saveAdmin,findByAdminId,updateAdmin,delAdmin,updateState } from '@/api/user'
import { roleTreeselect,toAdminAssignRole,getAdminRoleList} from '@/api/role'
// 导入分页公共组件
import Pagination from '@/components/Pagination'
import singleUpload from '@/components/upload/singleUpload.vue'
export default {
// import引入的组件需要注入到对象中才能使用
  components: {
    Pagination,
    singleUpload
  },
  // props实现父子组件传递数据
  props: {},
  data() {
    // 验证手机的自定义校验规则
    var checkPhone = (rule, value, callback) => {
      // 定义验证手机号码的正则表达式
      const regMobile = /^1\d{10}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法的手机号码'))
      }
    }
    // 这里存放数据
    return {
      // 用来保存t_admin管理员查询出来的分页列表信息
      list: null,
      // 用来保存分页时所需要的总记录数
      totalCount: 0,
      // 当发送异步请求用户列表数据时设置它为true,可出现正在加载中
      listLoading: true,
      query: {
        // 当前页码
        currPageNo: 1,
        // 每页显示的记录数
        pageSize: 2,
        // 查询条件，此处查询是以用户名和手机号码进行模糊查询
        name: '' ,
        sort:"+id"
      },
      // 添加用户的表单对象
      temp: {
        id: undefined,
        name: '',
        phone: '',
        telephone: '',
        address: '',
        state: 1,
        username: '',
        password: '',
        userFace: '',
        remark: ''
      },
      dialogFormVisible:false,
      rules: {
        name: [
          { required: true, message: '姓名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名的长度在2~10个字符之间', trigger: 'blur' }],
        phone: [
          { required: true, message: '手机号必填', trigger: 'blur' },
          /* validator: checkPhone 来调用data(){ }中定义的手机号格式校验规则 */
          { validator: checkPhone, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '登录名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '登录名的长度在2~10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '密码长度在3~15位之间', trigger: 'blur' }
        ]
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        assign: '分配角色'
      },

      // 角色菜单列表
      roleOptions: [],
      // 用于控制[分配角色对话框]的可见性
      dialogVisible: false,
      defaultProps: {
        label: 'nameZh'
      },
      // 分配角色对话框数据绑定到此对象中
      assignRole: {
        adminId: 0, // 操作员ID
        rid: [] // 角色列表，一个用户可以被分配多个角色
      },


    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
     // 调用查询管理员分页列表信息的方法
     this.getAdminList()
  },
  // 方法集合
  methods: {
    // 定义查询管理员分页列表信息的方法
    getAdminList() {
      // true时，表格中就会出现正在加载图标
      this.listLoading = true
      // 调用src/api/user.js中的pageUserList()
      pageUserList(this.query).then((res) => {
        this.listLoading = false
        this.list = res.data.list
        // 获取总记录数
        this.totalCount = res.data.totalCount
      }).catch((error) => {
        console.log(error)
        this.$message({
          title: '提示',
          message: '操作员列表查询失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    // 编辑按扭的点击事件
    handleUpdate(row) {
      //1.显示修改的模态框
      this.dialogFormVisible=true
      this.dialogStatus="update"
      this.resetTemp();
      //发送ajax请求
      findByAdminId(row.id)
        .then((res)=>{
          this.temp=res
        })
        .catch((err)=>{
          console.log(err);
        })
    },
    // 删除按扭的点击事件
    handleDelete(row, index) {
      this.$confirm('确认要删除当前操作员信息吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(()=>{
        delAdmin(row.id)
          .then((res)=>{
            if(res.code==200){
               // 弹框
               this.$message.success(res.message)
               // 刷新
               this.query.currPageNo=1;
               this.getAdminList()
            }else{
              this.$message.error(res.message)
            }
          })
          .catch((err)=>{
            console.log(err);
          })
      })
      .catch((err) => {
        this.$message.error(err)
      })


    },
    sortChange(data){
      const { prop, order } = data
      if(prop=="id"){
        this.sortByID(order);
      }
      if(prop=="name"){
        this.sortByName(order);
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.query.sort = '+id'
      } else {
        this.query.sort = '-id'
      }
      this.query.currPageNo = 1
      // 传到后端时this.query.sort的值为+id或为-id
      this.getAdminList()
    },
    sortByName(order) {
      if (order === 'ascending') {
        this.query.sort = '+name'
      } else {
        this.query.sort = '-name'
      }
      this.query.currPageNo = 1
      // 传到后端时this.query.sort的值为+id或为-id
      this.getAdminList()
    },
    // 重置Temp对象
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        phone: '',
        telephone: '',
        address: '',
        state: 1,
        username: '',
        password: '',
        userFace: '',
        remark: ''
      }
    },
    add(){
      this.dialogFormVisible=true
      this.dialogStatus="create"
      this.resetTemp()
    },
    insertData(){
      this.$refs["dataFormRef"].validate((valid)=>{
          if(valid){
            saveAdmin(this.temp)
              .then((res)=>{
                 //关闭新增的模态框
                 this.dialogFormVisible=false;
                 if(res.code==200){
                    //弹出提示信息
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'success',
                      duration: 2000
                    })
                    //刷新列表数据
                    this.getAdminList();
                 }else{
                    //弹出提示信息
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    })
                 }

              })
              .catch((err)=>{
                console.log(err)
              });
          }
      });
     
    },
    // 添加操作员信息对话框中的取消按扭点击事件
    cancelEvent() {
      this.dialogFormVisible = false
    },
    adminStateChange(row){
      updateState(row)
        .then((res)=>{
            if(res.code==200){
              //弹出提示信息
              this.$message({
                title: '提示',
                message: res.message,
                type: 'success',
                duration: 2000
              })
            }else{
              //弹出提示信息
              this.$message({
                title: '提示',
                message: res.message,
                type: 'error',
                duration: 2000
              })
            }
        })
        .catch((err)=>{
          console.log(err);
        })
    },
    toAssignRole(row){
      this.dialogVisible=true;
      this.dialogStatus="assign"
      //设置用户id
      this.assignRole.adminId=row.id;
      //查询所有的角色
      roleTreeselect()
        .then((res)=>{
          this.roleOptions=res;
        })
        .catch((err)=>{
          console.log(err);
        })
      //查询当前用户所拥有的角色
      getAdminRoleList(row.id)
        .then((res)=>{
          this.$refs["roleRef"].setCheckedKeys([])
          if (res.rid) {
            // 角色树结构中默认选中当前操作员现有的角色
            this.$refs["roleRef"].setCheckedKeys(res.rid)
          }
        })
        .catch((err)=>{
          console.log(err);
        })
    },
    confirmAssign(){
      //获取选中的角色
      const checkKeys=this.$refs["roleRef"].getCheckedKeys();
      if(checkKeys.length>0){
        this.assignRole.rid=checkKeys;

        toAdminAssignRole(this.assignRole)
          .then((res)=>{
              if(res.code==200){
                this.$message({
                  title: '提示',
                  message: res.message,
                  type: 'success',
                  duration: 2000
                });
                this.dialogVisible=false;

              }else{
                this.$message({
                  title: '提示',
                  message: res.message,
                  type: 'error',
                  duration: 2000
                })
              }
          })
          .catch((err)=>{
            console.log(err);
          })

      }else{
        this.$message({
            title: '提示',
            message: '请选择要分配的角色',
            type: 'info',
            duration: 2000
          })
        }
      }

     
    },
    updateData(){
      this.$refs["dataFormRef"].validate((valid)=>{
          if(valid){
            updateAdmin(this.temp)
              .then((res)=>{
                 //关闭新增的模态框
                 this.dialogFormVisible=false;
                 if(res.code==200){
                    //弹出提示信息
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'success',
                      duration: 2000
                    })
                    //刷新列表数据
                    this.getAdminList();
                 }else{
                    //弹出提示信息
                    this.$message({
                      title: '提示',
                      message: res.message,
                      type: 'error',
                      duration: 2000
                    })
                 }

              })
              .catch((err)=>{
                console.log(err)
              });
          }
      });
    }

  }
</script>
<style scoped>

</style>
